/**
* File:          dvdidToXml.c
* Author:        Brian Patrick Burns
* Last revision: 2011-04-02
*
* This program takes a computed CRC64 value from a program such as dvdid.exe 
* and formats a dvdid.xml file for use with Windows Media Center.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dvdidToXml.h"

#define MAX_OPT (2)
#define MIN_OPT (2)

/**
* Main entry point of program
* 
*/
int main(int argc, char *argv[])
{
	char* xmlString;

	if (!checkArgs(argc, argv))
	{
		fprintf(stderr, "Error: Invocation requires exactly two (2) argumemts.");
		return(EXIT_FAILURE);
	}

	xmlString = xmlFromID(argv[1], argv[2]);
	printf(xmlString);
	printf("\n");

	free(xmlString);
	return(EXIT_SUCCESS);
}

/**
* checkArgs
*
* This function checks the program invocation arguments to ensure that the
* program was invoked correctly by the user on the command line.
*/
int checkArgs(int argc, char *argv[])
{
	// for now, only very simple error checking
	if ( argc < (MIN_OPT + 1) || argc > (MAX_OPT + 1) ) 
	{
		return FALSE;
	}
	else
	{
		return TRUE;
	}
}

/**
* xmlFromID
*
* Returns a string suitable for output to a file from the dvdid specified in 
* dvdID
* 
* The memory allocated for the returned string needs to be freed when the
* caller has finished using it.
*
* @param  label the DVD Label value
* @param  dvdID the CRC64 value calculated for the disk
* @return char* representation of the file
*/
char* xmlFromID(char* label, char* id)
{
	char *beforeLabel, *afterLabelBeforeID, *afterID;
	int size, i;
	char *xml; // the xml output of our function

	// hard-coded values that form a template of sorts for a dvdid.xml file
	beforeLabel = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Disc>\n	<Name>";
	afterLabelBeforeID = "</Name>\n	<ID>";
	afterID = "</ID>\n</Disc>";

	// calculate total size of the string
	size = 0;
	size += strlen(beforeLabel);
	size += strlen(label);
	size += strlen(afterLabelBeforeID);
	size += strlen(id);
	size += strlen(afterID);
	// size now holds the length of the string that we need

	// allocate and clean out string
	xml = (char*) malloc(size + 1);
	xml[0] = '\0'; // ensure that strcat doesn't write junk in the first index

	// assemble our xml string
	strcat(xml, beforeLabel);
	strcat(xml, label);
	strcat(xml, afterLabelBeforeID);
	strcat(xml, id);
	strcat(xml, afterID);

	return xml;
}

/**
* printError
*
* Prints a formatted message to stderr
*
* @param message a null-terminated string to be printed to stderr
*/
void printError(char *invocation, char *message)
{
}

/**
* printUsage
*
* Prints a message indicating the correct CLI invocation of the program
*/
void printUsage()
{
	return;
}